package com.ysu.his.admin.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.ysu.his.admin.service.ValidateCodeService;
import com.ysu.his.constant.RedisConstant;
import com.ysu.his.vo.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService
{
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public ValidateCodeVo generateValidateCode()
    {
        //1.通过工具生成图片验证码 hutool
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 2);
        String code = circleCaptcha.getCode();//4位验证码的值;
        String imageBase64 = circleCaptcha.getImageBase64();//返回图片验证码，Base64编码方式

        //2.把验证码存到redis 设置key，value ttl
        String key = UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(RedisConstant.USER_VALIDATACODE +key,
                code,
                RedisConstant.USER_VALIDATA_TTL,
                TimeUnit.SECONDS);

        //3.返回Vo对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(key);
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);

        return validateCodeVo;
    }
}
